import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/token'

// 路由
// import Login from '@/views/Login'
// import Layout from '@/views/Layout'
// import Home from '@/views/Home'
// import User from '@/views/User'
// import Search from '@/views/Search'
// import SearchResult from '@/views/Search/SearchResult'
// import ArticleDetail from '@/views/ArticleDetail'
// import UserEdit from '@/views/User/UserEdit'
// import Chat from '@/views/Chat'

Vue.use(VueRouter)

// 使用路由懒加载
const routes = [
  {
    path: '/',
    redirect: '/layout/home'
  }, {
    path: '/login',
    component: () => import(/* webpackChunkName: "Login" */'@/views/Login'),
    // 路由的独享守卫
    beforeEnter: (to, from, next) => {
      if (getToken()?.length > 0) { // 有token，并且去登录页面，阻止他去
        next('/layout/home')// 去往主页
      } else { next() }
    }
  }, {
    path: '/layout',
    component: () => import(/* webpackChunkName: "Layout" */'@/views/Layout'),
    children: [
      {
        path: 'home',
        component: () => import(/* webpackChunkName: "Home" */'@/views/Home'),
        meta: {
          scrollT: 0// 保存首页离开时的位置
        }
      }, {
        path: 'user',
        component: () => import(/* webpackChunkName: "User" */'@/views/User')
      }
    ]
  }, {
    // 搜索页
    path: '/search',
    component: () => import(/* webpackChunkName: "Search" */'@/views/Search')
  }, {
    // 搜索结果页【传递参数方法1：路径传值】
    path: '/search_result/:kw',
    component: () => import(/* webpackChunkName: "SearchResult" */'@/views/Search/SearchResult')
  }, {
    // 文章详情页【传递参数方法2:问号拼接】
    path: '/detail',
    component: () => import(/* webpackChunkName: "ArticleDetail" */'@/views/ArticleDetail')
  }, {
    // 修改用户资料页面
    path: '/user_edit',
    component: () => import(/* webpackChunkName: "UserEdit" */'@/views/User/UserEdit')
  }, {
    // 聊天页面
    path: '/chat',
    component: () => import(/* webpackChunkName: "Chat" */'@/views/Chat')
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫————用于确认是否含有token，若无则跳转回Login页面
// router.beforeEach((to, from, next) => {
//   // to：表示访问的路径
//   // from：表示从哪个路径跳转而来
//   // next：是一个函数，表示放行
//   if (getToken()?.length > 0 && to.path === '/login') { // 有token，并且去登录页面，阻止他去
//     next('/layout/home')// 去往主页
//   } else { next() }
// })
export default router
